// as early as possible in your application
// require and configure dotenv
require('dotenv').config()

const koa = require('koa')
const logger = require('koa-logger')
const api = require('./routes/api')

const app = koa()

app.use(logger())

app.use(function* (next) {
  try {
    yield next
  }
  catch (err) {
    this.status = err.status || 500
    this.type = 'json'
    this.body = {
      error: true,
      msg: err.message || 'An error occured',
    }
  }
})

// application route
app.use(api.routes())

app.use(function* resourceNotFound() {
  this.status = 404

  this.body = {
    error: true,
    msg: '404 Not Found',
  }
})

if (!module.parent) {
  app.listen(process.env.PORT || 1234)
}

module.exports = app
